package com.learn.training.multithread.chapter12.demo1;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Demo2 {

    static List<Integer> list = new ArrayList<Integer>();

    public static void main(String[] args) {
        ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
        ses.scheduleAtFixedRate(() -> {
            ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
            ThreadInfo[] threadInfo = threadMXBean.dumpAllThreads(false, false);
            updateMaxThreadNum(threadInfo.length);
        }, 10, 10, TimeUnit.MILLISECONDS);

        long startTime = System.currentTimeMillis();

        // 使用虚拟线程池
        ExecutorService es = Executors.newVirtualThreadPerTaskExecutor();

        // 使用平台线程池
//        ExecutorService es = Executors.newFixedThreadPool(200);

        for (int i = 0; i < 10000; i++) {
            es.submit(() -> {
                try {
                    TimeUnit.MILLISECONDS.sleep(500);
                }catch (InterruptedException e) {e.printStackTrace();}
            });
        }

        es.close();
        System.out.println("max :  "+ list.get(0) + " platform thread/os thread");
        System.out.printf("totalMillis :  %dms \n", System.currentTimeMillis() - startTime );

    }


    public static void updateMaxThreadNum(int n) {
        if (list.isEmpty()){
            list.add(n);
        }else {
            Integer integer = list.get(0);
            if (n > integer){
                list.add(n);
            }else {
                Integer integer1 = list.get(0);
                if (n > integer1){
                    list.add(0, n);
                }
            }
        }
    }
}
